package com.benshou.bsoa.common.trace;

import org.springframework.util.StringUtils;

import java.time.ZoneId;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户上下文工具类
 */
public class UserContext {
    // 属性键名常量
    private static final String KEY_USER_ID = "userId";
    private static final String KEY_USER_COMP_ID = "userCompId";
    private static final String KEY_USER_DEPT_ID = "userDeptId";
    private static final String KEY_USER_ROLE_IDS = "userRoleIds";
    private static final String KEY_CLIENT_TIMEZONE = "clientTimezone";
    
    // 使用单个ThreadLocal存储所有用户上下文信息
    private static final ThreadLocal<Map<String, Object>> CONTEXT = ThreadLocal.withInitial(HashMap::new);

    public static void setUserId(String userId) {
        CONTEXT.get().put(KEY_USER_ID, userId);
    }

    public static String getUserId() {
        return (String) CONTEXT.get().get(KEY_USER_ID);
    }

    public static void setUserCompId(String compId) {
        CONTEXT.get().put(KEY_USER_COMP_ID, compId);
    }

    public static String getUserCompId() {
        return (String) CONTEXT.get().get(KEY_USER_COMP_ID);
    }

    public static void setUserDeptId(String deptId) {
        CONTEXT.get().put(KEY_USER_DEPT_ID, deptId);
    }

    public static String getUserDeptId() {
        return (String) CONTEXT.get().get(KEY_USER_DEPT_ID);
    }

    public static void setUserRoleIds(String roleIds) {
        if (roleIds != null && !roleIds.isEmpty()) {
            CONTEXT.get().put(KEY_USER_ROLE_IDS, Arrays.asList(roleIds.split(",")));
        }
    }

    @SuppressWarnings("unchecked")
    public static List<String> getUserRoleIds() {
        return (List<String>) CONTEXT.get().get(KEY_USER_ROLE_IDS);
    }

    public static void setClientTimezone(String timezone) {
        CONTEXT.get().put(KEY_CLIENT_TIMEZONE, timezone);
    }

    public static String getClientTimezone() {
        String timezone = (String) CONTEXT.get().get(KEY_CLIENT_TIMEZONE);
        return StringUtils.hasText(timezone)
                ? timezone
                : ZoneId.systemDefault().getId(); // 系统默认时区
    }

    /**
     * 清除当前线程的所有用户上下文信息
     */
    public static void clear() {
        CONTEXT.get().clear();
    }
}